package cn.zhz.controller;

import cn.zhz.pojo.Role;
import cn.zhz.pojo.User;
import cn.zhz.service.role.RoleService;
import cn.zhz.service.user.UserService;
import cn.zhz.tools.Constants;
import cn.zhz.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    private Logger logger = Logger.getLogger(UserController.class);
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String doLogin(@RequestParam(value = "userCode",required = false)String userCode,
                          @RequestParam(value = "userPassword",required = false)String userPassword,
                          HttpServletRequest request,HttpSession session){
        User user=userService.loginUser(userCode, userPassword);
        if (user == null) {
            session.setAttribute("error", "用户名或密码不正确！");
            return "login";
        }else{
            session.setAttribute("error", " ");
        }
        session.setAttribute(Constants.USER_SESSION, user);
        return "frame";
    }

    @RequestMapping(value = "/list")
    public String getUserList(Model model,
                              @RequestParam(value="queryname",required=false) String queryUserName,
                              @RequestParam(value="queryUserRole",required=false) String queryUserRole,
                              @RequestParam(value="pageIndex",required=false) String pageIndex)throws Exception{
        int _queryUserRole = 0;
        List<User> userList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;

        if(queryUserName == null){
            queryUserName = "";
        }
        if(queryUserRole != null && !queryUserRole.equals("")){
            _queryUserRole = Integer.parseInt(queryUserRole);
        }

        if(pageIndex != null){
            try{
                currentPageNo = Integer.valueOf(pageIndex);
            }catch(NumberFormatException e){
                return "redirect:/user/syserror.html";
                //response.sendRedirect("syserror.jsp");
            }
        }
        //总数量（表）
        int totalCount	= userService.getUserCount(queryUserName,_queryUserRole);
        //总页数
        PageSupport pages=new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);
        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if(currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        userList = userService.getUserList(queryUserName,_queryUserRole,currentPageNo,pageSize);
        model.addAttribute("userList", userList);
        List<Role> roleList = null;
        roleList = roleService.getRoleList();
        model.addAttribute("roleList", roleList);
        model.addAttribute("queryUserName", queryUserName);
        model.addAttribute("queryUserRole", queryUserRole);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        return "userlist";
    }
    @RequestMapping(value = "/useradd")
    public String UserAdd(){
        return "useradd";
    }

    @RequestMapping(value = "/addsave",method = RequestMethod.POST)
    public String addUserSave(HttpServletRequest request, HttpSession session, @RequestParam(value = "attachs",required = false)MultipartFile[] attachs,User user){
        String idPicPath=null;
        String workPicPath=null;
        String errorInfo=null;
        boolean flag=true;
        String path=request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");


        //判断文件是否为空
        for (int i = 0; i <attachs.length ; i++) {
            MultipartFile attach=attachs[i];
            if (!attach.isEmpty()){
                if(i==0){
                    errorInfo="uploadFileError";
                }else if(i==1){
                    errorInfo="uploadWpError";
                }
                String oldFileName=attach.getOriginalFilename();//原文件名
                //logger.info("uploadFile  oldFileName====>"+oldFileName);
                String prefix=FilenameUtils.getExtension(oldFileName);//原文件名后缀
                //logger.info("uploadFile  prefix====>"+prefix);
                int filesize=5000000;
                //logger.debug("uploadFile  filesize====>"+attach.getSize());
                if(attach.getSize()>filesize){
                    request.setAttribute("errorInfo","上传大小不得超过5000kb");
                    flag=false;
                }else if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpeg")
                        ||prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
                    String fileName=System.currentTimeMillis()+RandomUtils.nextInt(0,1000000)+"_Personal.jpg";
                    File targetFile=new File(path,fileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(targetFile);
                    }catch (Exception e){
                        e.printStackTrace();
                        request.setAttribute("errorInfo","上传失败！");
                        flag=false;
                    }
                    if(i==0){
                        idPicPath=File.separator+fileName;
                    }else if(i==1){
                        workPicPath=File.separator+fileName;
                    }
                    logger.debug("idPicPath:"+idPicPath);
                    logger.debug("workPicPath:"+workPicPath);
                }else{
                    request.setAttribute("errorInfo","*上传图片格式不正确");
                    flag=false;
                }
            }
        }
        if(flag){
            user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
            user.setCreationDate(new Date());
            user.setIdPicPath(idPicPath);
            user.setWorkPicPath(workPicPath);
            if(userService.addUser(user)>0){
                return "redirect:/user/list";
            }
        }
        return "useradd";
    }


    @RequestMapping(value = "/updateUser",method = RequestMethod.POST)
    public String UpdateUser(User user,HttpSession session){
        logger.debug("modifyUserSave userid========"+user.getId());
//        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
//        user.setModifyDate(new Date());
        if(userService.updateUser(user)){
            return "redirect:/user/list";
        }
        return "usermodify";

    }
    @RequestMapping(value = "/usermodify",method = RequestMethod.GET)
    public String getUserById(@RequestParam int uid,Model model){
        logger.debug("getUserById uid========"+uid);
        User user=userService.UserId(uid);
        model.addAttribute("user",user);
        return "usermodify";
    }
    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public String showView(@PathVariable int id,Model model){
        logger.debug("showView id=============="+id);
        User user=userService.UserId(id);
        model.addAttribute(user);
        return "userview";
    }
    @RequestMapping(value = "/view",method = RequestMethod.GET)
    @ResponseBody
    public User view(@RequestParam(value = "id")int id){
        logger.debug("view id:"+id);
        String cjson="";
        User user=new User();
        try {
            user=userService.UserId(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    @RequestMapping(value = "/delUser",method=RequestMethod.GET)
    @ResponseBody
    public Object DeleUser(@RequestParam int uid){

        HashMap<Object,String > map=new HashMap<Object, String>();
        if (userService.delUser(uid)>0){
            map.put("delResult","true");
        }else{
            map.put("delResult","false");
        }
        return JSONArray.toJSONString(map);
    }


    @RequestMapping(value = "/homePage")
    public String homePage() {
        return "frame";
    }
    //跳转修改页面
    @RequestMapping(value="/PwdModify")
    public String goPwdModify() {
        return "pwdmodify";
    }
    //异步验证后台对比密码
    @RequestMapping(value="/checkPwd",method=RequestMethod.GET)
    @ResponseBody
    public Object checkPwd(@RequestParam String oldpassword,HttpSession session) {
        //获取登陆对象
        HashMap<String,Object>map=new HashMap<String, Object>();
        if (oldpassword=="" || oldpassword==null) {
            map.put("result","error");
        }else if (session.getAttribute(Constants.USER_SESSION)==null) {
            map.put("result","sessionerror");
        }else {
            int uid=((User)session.getAttribute(Constants.USER_SESSION)).getId();
            User user=userService.UserId(uid);
            if (user.getUserPassword().equals(oldpassword)) {
                map.put("result","true");
            }else {
                map.put("result","false");
            }
        }
        return JSONArray.toJSONString(map);
    }
    @RequestMapping(value="/ESC")
    public String ESC(HttpSession session) {
        session.removeAttribute(Constants.USER_SESSION);
        return "login";

    }
    //修改密码
    @RequestMapping(value="/updatePwd")
    public String updatePwd(@RequestParam("newpassword")String newpassword,HttpSession session) {
        try {
            int uid=((User)session.getAttribute(Constants.USER_SESSION)).getId();
            if (userService.updatePwd(uid, newpassword)>0) {
                return "frame";
            }else {
                return "pwdmodify";
            }
        } catch (Exception e) {
            return "pwdmodify";
        }
    }
}
